import java.util.Arrays;

public class Leetcode828 {

    public static void main(String[] args) {
        System.out.println(uniqueLetterString("ABC"));
        System.out.println(uniqueLetterString("ABA"));
        System.out.println(uniqueLetterString("LEETCODE"));
    }

    public static int uniqueLetterString(String s) {
        int res = 0;
        boolean[] flags = new boolean[26];

        char[] sChars = s.toCharArray();
        for (char sChar : sChars) {
            flags[sChar - 'A'] = true;
        }

        loop:
        for (char i = 'A'; i <= 'Z'; i++) {
            if (!flags[i - 'A']) {
                continue;
            }

            int left = 0, right = -1;

            for (int j = 0; j < sChars.length; j++) {
                if (sChars[j] == i) {
                    left = right;
                    right = j;
                    res += (right - left) * (right + Math.abs(left)) / 2;
                    if (j == sChars.length - 1) {
                        continue loop;
                    }
                }
            }

            res += (sChars.length - right) * (right + sChars.length) / 2;

        }


        return res;
    }

}
